package model

import (
	"OJCenter/global"
	"OJCenter/idl"
	"errors"
	"github.com/mitchellh/mapstructure"
)

func (m *Model) CreateUser(user *idl.User) error {
	err := m.U.InsertUserInfo(user)
	if err != nil {
		return err
	}
	return nil
}

func (m *Model) DeleteUsers(uids *[]int64) (int, *[]int64) {
	sum := len(*uids)
	var fu []int64
	for _, uid := range *uids {
		err := m.U.DeleteUserInfo(&idl.User{Uid: uid})
		if err != nil {
			sum--
			fu = append(fu, uid)
			global.Logger.Errorf("uid:%v,delete user info failed,err:%v", uid, err)
		}
	}
	return sum, &fu
}

func (m *Model) UpdateUsers(Users *[]idl.User) (int, *[]idl.User) {
	sum := len(*Users)
	var fu []idl.User
	for _, user := range *Users {
		var info map[string]interface{}
		err := mapstructure.Decode(&user, &info)
		if err != nil {
			fu = append(fu, user)
			global.Logger.Error("update marshal failed")
			sum--
			continue
		}
		err = m.U.UpdateUserInfoByID(info)
		if err != nil {
			sum--
			fu = append(fu, user)
			global.Logger.Errorf("uid:%v,update Problem info failed,err:%v", user.Uid, err)
		}
	}
	return sum, &fu
}

func (m *Model) CheckAuth(uid int64, pwd string) (*map[string]string, error) {
	Info, err := m.U.GetUserInfoWithRedis(uid)
	if err != nil {
		return nil, errors.New("get user info with redis failed")
	}
	_pwd, ok := (*Info)["pwd"]
	if !ok {
		return nil, errors.New("get pwd failed")
	}
	if _pwd != pwd {
		return nil, errors.New("pwd is error")
	}
	return Info, nil
}

func (m *Model) GetUserList(page, limit int) (*[]idl.User, error) {
	return m.U.GetUserList(page, limit)
}

func (m *Model) SelectUsers(user idl.User) (*[]idl.User, error) {
	return m.U.SelectUsers(&user)
}

//func (m *Model) IsCacheHasUser(uid int64)bool{
//	has,err:= m.U.IsCacheHasUInfo(uid)
//	if err!=nil{
//		global.Logger.Errorf("get user cache err:%v",err)
//	}
//	return has
//}
